package com.chen.pfm.slice;

import com.chen.pfm.ResourceTable;
import com.chen.pfm.entity.DisplayBill;
import com.chen.pfm.entity.ReportForms;
import com.chen.pfm.provider.DisplayBillProvider;
import com.chen.pfm.provider.ReportFormProvider;
import com.chen.pfm.provider.TitleProvider;
import com.chen.pfm.utils.ClassifyDBUtil;
import com.chen.pfm.utils.DateUtils;
import com.chen.pfm.utils.MyToast;
import com.chen.pfm.utils.MyUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ListDialog;
import ohos.app.AbilityContext;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_CONTENT;

public class SearchAbilitySlice extends AbilitySlice {
    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x2022002, "SearchAbilitySlice");
    ListContainer searchListContainer;
    int searchType = 0;//筛选
    Text select_condition;//筛选条件
    TextField search_TextField;//搜索输入框
    Image search;
    List<DisplayBill> displayBillList;//数据渲染
    DisplayBillProvider displayBillProvider;//搜索数据渲染配置器
    DisplayBill item;//搜索展示数据的那一项
    int itemPosition;//搜索展示数据的那一项的索引
    DisplayBill displayBill;//更改数据重新加入的数据项

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_search);
        searchListContainer = (ListContainer) findComponentById(ResourceTable.Id_search_ListContainer);
        search = (Image) findComponentById(ResourceTable.Id_search);
        select_condition = (Text) findComponentById(ResourceTable.Id_select_condition);
        search_TextField = (TextField) findComponentById(ResourceTable.Id_search_TextField);
        //事件监听
        select_condition.setClickedListener(component -> showPickSearchTypeType(this));
        search.setClickedListener(component -> confirmSearch());

    }

    //搜索
    public void confirmSearch() {
        String search = search_TextField.getText();
        if (search == null || search.equals("")) {
            MyToast.showMyToast(this, "搜索内容为空");
            return;
        }

        try {
            displayBillList = MyUtil.searchDisplayBillByCondition(this, search, searchType);
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        }
        if (displayBillList == null) {
            MyToast.showMyToast(this, "搜索数据为空！");
            return;
        } else {
            showSearchResult();
        }
    }


    public void showSearchResult() {
        Collections.sort(displayBillList, new Comparator<DisplayBill>() {
            @Override
            public int compare(DisplayBill o1, DisplayBill o2) {
                //这里使用时间字段排序 如果要用其他字段直接从bean实体中取
                return o2.getRecordTime().compareTo(o1.getRecordTime());
                //上面使用的是降序排序，如果正序 直接使用o1-o2即可
            }
        });
        displayBillProvider = new DisplayBillProvider(displayBillList, this);
        searchListContainer.setItemProvider(displayBillProvider);

        //设置响应点击事件
        searchListContainer.setItemClickedListener((container, component, position, id) -> {
            item = (DisplayBill) searchListContainer.getItemProvider().getItem(position);
            itemPosition = position;
            if (item == null) {
                return;
            }
            //跳转
            Intent intent = new Intent();
            intent.setParam("Aid", item.getAid());
            presentForResult(new BillDetailsSlice(), intent, 1004);
        });

        //数据改变监听事件
        searchListContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                displayBillProvider.notifyDataChanged();
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
            }
        });
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        if (requestCode == 1004) {
            if (resultIntent != null) {
                String op = resultIntent.getStringParam("op");
                if (op == null) {
                    return;
                }
                if (op.equals("del")) {
                    displayBillList.remove(itemPosition);
                    //数据改变监听事件
                    searchListContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {
                            // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                            // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
                            displayBillProvider.notifyDataSetItemRemoved(itemPosition);
                            // displayBillProvider.notifyDataChanged();
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else if (op.equals("update")) {
                    String aid = resultIntent.getStringParam("aid");
                    try {
                        displayBill = MyUtil.queryDisplayBillByAid(this, aid);
                    } catch (DataAbilityRemoteException e) {
                        e.printStackTrace();
                    }
                    displayBillList.remove(itemPosition);
                    displayBillList.add(itemPosition, displayBill);
                    //数据改变监听事件
                    searchListContainer.setBindStateChangedListener(new Component.BindStateChangedListener() {
                        @Override
                        public void onComponentBoundToWindow(Component component) {
                            // ListContainer初始化时数据统一在provider中创建，不直接调用这个接口；
                            // 建议在onComponentBoundToWindow监听或者其他事件监听中调用。
                             displayBillProvider.notifyDataSetItemChanged(itemPosition);
                        }

                        @Override
                        public void onComponentUnboundFromWindow(Component component) {
                        }
                    });
                } else {

                }


            }


        }
    }

    //搜索条件
    public void showPickSearchTypeType(AbilityContext context) {
        //分类类型
        getUITaskDispatcher().asyncDispatch(() -> {
            ListDialog listDialog = new ListDialog(context, ListDialog.SINGLE);
            listDialog.setCornerRadius(45);
            listDialog.getProvider();
            listDialog.setSize(800, MATCH_CONTENT);
            String[] strings = {"模糊搜索"};
            List<String> titles = new ArrayList<>();
            titles.add("模糊搜索");
            titles.add("金额");
            titles.add("日期");
            titles.add("备注");
            listDialog.setItems(strings);
            TitleProvider titleProvider = new TitleProvider(titles, this);
            listDialog.setProvider(titleProvider);
            listDialog.setButton(0, "取消", (iDialog, i) -> {
                iDialog.hide();
                MyToast.showMyToast(this, "已取消");

            });
            //展示
            listDialog.show();
            //监听
            ((ListContainer) listDialog.getListContainer()).setItemSelectedListener((listContainer, component, i, l) -> {
                MyToast.showMyToast(this, "你选择了" + titles.get(i));
                searchType = i;
                select_condition.setText(titles.get(i));
                //改变渲染数据
                listDialog.hide();
            });
        });
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
